<template>
  <div class="users-root">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 2、卡片视图 -->
    <el-card class="box-card">
      <!-- 搜索框，添加按钮 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入用户名"
            v-model="pageInfo.query"
            class="input-with-select"
            :clearable="true"
            @clear="clearInput"
          >
            <el-button slot="append" icon="el-icon-search" @click="getUserList()"></el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" @click="addUserDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户表格 :data绑定userList数据 -->
      <el-table :data="userList" border style="width: 100%" :headerCellStyle="headerCellStyle">
        <!-- 序号 -->
        <el-table-column type="index" label="序号" width="100" align="center"> </el-table-column>
        <el-table-column prop="username" label="用户名" width="150" align="center"> </el-table-column>
        <el-table-column prop="email" label="邮箱" width="240" align="center"> </el-table-column>
        <el-table-column prop="role_name" label="角色" width="140" align="center"> </el-table-column>
        <el-table-column prop="mg_state" label="状态" width="140" align="center">
          <!-- ！！！！作用域插槽 scope.row是当前行对应的元素对象！！！！ -->
          <template v-slot="scope">
            <!-- 开关组件v-model绑定是当前这一行对象的mg_state，true显示绿色，false显示红色 -->
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              @change="changeUserState(scope.row)"
              inactive-color="#ff4949"
            ></el-switch>
          </template>
        </el-table-column>
        <!-- 管理 -->
        <el-table-column label="管理" align="center">
          <template v-slot="scope">
            <el-tooltip class="item" effect="dark" content="编辑用户" placement="top" :enterable="false">
              <el-button
                type="primary"
                icon="el-icon-edit"
                circle
                size="mini"
                @click="showEditUser(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除用户" placement="top" :enterable="false">
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                size="mini"
                @click="delUserById(scope.row)"
              ></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="修改角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-setting"
                circle
                size="mini"
                @click="showgrantRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 2-3 分页器 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageInfo.pagenum"
        :page-sizes="[1, 5, 10, 15]"
        :page-size="pageInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.total"
      >
      </el-pagination>
    </el-card>
    <!-- 3、添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="addUserDialogVisible" width="7rem" @close="addUserDialogClose()">
      <!-- 添加用户的表单 -->
      <el-form :model="addUserForm" :rules="addUserRules" ref="addUserFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 页脚 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUsers()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 4、修改用户对话框 -->
    <el-dialog title="修改用户" :visible.sync="editUserDialogVisible" width="7rem" @close="editUserDialogClose()">
      <!-- 添加用户的表单 -->
      <el-form :model="editUserForm" :rules="addUserRules" ref="editUserFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editUserForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 页脚 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="grantRoleDialogVisible" width="7rem" @close="grantRoleDialogClose()">
      <!-- 表单 -->
      <el-form
        :model="grantRoleForm"
        :rules="grantRoleFormrules"
        ref="grantRoleFormeRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名称">
          <el-input style="width:2.22rem" v-model="grantRoleForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="角色列表" prop="rid">
          <el-select v-model="grantRoleForm.rid" placeholder="请选择活动区域">
            <el-option
              :label="item.roleName"
              :value="item.id"
              v-for="(item, index) in roleList"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 页脚 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="grantRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="grantRole()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request from '../../utils/request'
export default {
  data() {
    //验证用户名的规则
    let validUsername = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('用户名不能空'))
      }
      rule = /^[a-zA-Z]{3,15}$/
      if (!rule.test(value)) {
        return callback(new Error('用户名3-15个英文字符'))
      }
      //放行
      callback()
    }
    //验证密码的规则
    let validPassword = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('密码不能空'))
      }
      rule = /^[a-zA-Z\d]{6,12}$/
      if (!rule.test(value)) {
        return callback(new Error('密码6-12个字符'))
      }
      //放行
      callback()
    }
    //验证邮箱的规则
    let validEmail = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('邮箱不能空'))
      }
      rule = /^[a-zA-Z0-9]+@[a-zA-Z0-9]{2,}(\.com|.cn|\.com\.cn|\.org|\.net|\.edu)$/
      if (!rule.test(value)) {
        return callback(new Error('非法的邮箱'))
      }
      //放行
      callback()
    }
    //验证电话的规则
    let validMobile = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('电话不能空'))
      }
      rule = /^1[356789]\d{9}$/
      if (!rule.test(value)) {
        return callback(new Error('非法的电话'))
      }
      //放行
      callback()
    }
    return {
      //控制对话框是否显示
      grantRoleDialogVisible: false,
      //角色列表
      roleList: [],
      //分配角色的表单数据源
      grantRoleForm: {
        uid: '',
        rid: '',
        username: ''
      },
      //分配角色表单的验证规则
      grantRoleFormrules: {
        rid: [{ required: true, message: '请选择角色名称', trigger: 'change' }]
      },
      //分页参数
      pageInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5,
        total: 0
        //totalpage: 0
      },
      userList: [],
      //3、表头的样式
      headerCellStyle: {
        backgroundColor: '#409EFF',
        color: '#ffffff',
        textAlign: 'center'
      },
      //4、控制添加用户对话框是否显示的标记
      addUserDialogVisible: false,
      //5、添加用户表单对应的数据源
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      //6、添加用户的表单验证规则
      addUserRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { validator: validUsername, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: validPassword, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: validEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: validMobile, trigger: 'blur' }
        ]
      },
      //7、修改用户对话框表单数据源
      editUserForm: {
        id: '',
        username: '',
        email: '',
        mobile: ''
      },
      //8 、控制修改对话框是否显示标记
      editUserDialogVisible: false
    }
  },
  methods: {
    //显示分配角色对话框
    async showgrantRole(user) {
      //把分配角色的对象信息保存到data中
      this.grantRoleForm.uid = user.id
      this.grantRoleForm.username = user.username
      //获得所有角色列表
      let options = { url: 'roles', type: 'get' }
      let { data: res } = await request(options)
      this.roleList = res.data
      //显示对话框
      this.grantRoleDialogVisible = true
    },
    //分配角色
    async grantRole() {
      let options = {
        url: `users/${this.grantRoleForm.uid}/role`,
        type: 'put',
        data: { rid: this.grantRoleForm.rid }
      }
      let { data: res } = await request(options)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('设置角色成功')
      //隐藏对话框
      this.grantRoleDialogVisible = false
      //重新加载数据
      this.getUserList()
    },
    //分配角色对话框消失执行的操作
    grantRoleDialogClose() {
      //重置表单
      let form = this.$refs['grantRoleFormeRef']
      form.resetFields()
    },
    //清空输入框时触发的函数
    clearInput() {
      this.getUserList()
    },
    async getUserList() {
      let option = {
        url: 'users',
        type: 'get',
        data: this.pageInfo
      }
      let { data: res } = await request(option)
      console.log(res)
      this.userList = res.data.users
      console.log(this.userList)
      this.pageInfo.total = res.data.total
    },
    //修改用户的状态
    async changeUserState(user) {
      console.log(user)
      let option = {
        type: 'put',
        url: `users/${user.id}/state/${user.mg_state}`
      }
      let { data: res } = await request(option)
      console.log(res)
      //设置失败的提示
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success(res.meta.msg)
    },
    //页面显示条数变换执行的函数
    handleSizeChange(pagesize) {
      this.pageInfo.pagesize = pagesize
      this.getUserList()
    },
    //页码发生变化执行的函数
    handleCurrentChange(pagenum) {
      this.pageInfo.pagenum = pagenum
      this.getUserList()
    },
    //5、添加用户对话框关闭时触发的事件
    addUserDialogClose() {
      console.log('addUserDialogClose')
      //找到表单
      let form = this.$refs['addUserFormRef']
      //重置表单
      form.resetFields()
    },
    //6.添加用户
    addUsers() {
      //表单验证
      let form = this.$refs['addUserFormRef']
      form.validate(async valid => {
        if (!valid) {
          return this.$message.error('请正确填写用户信息')
        }
        let option = {
          url: 'users',
          type: 'post',
          data: this.addUserForm
        }
        let { data: res } = await request(option)
        console.log(res)
        //添加失败
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.msg)
        }
        //添加成功
        this.$message.success('添加成功')
        //关闭对话框
        this.addUserDialogVisible = false
        //重新加载数据
        this.getUserList()
      })
    },
    //7、显示编辑用户对话框
    showEditUser(user) {
      console.log(user)
      //user的属性全部赋值给this.editUserForm
      Object.assign(this.editUserForm, user)
      //显示修改对话框
      this.editUserDialogVisible = true
    },
    //8、修改对话框隐藏时触发的操作
    editUserDialogClose() {},
    //9、修改用户信息
    editUser() {
      //表单验证
      let form = this.$refs['editUserFormRef']
      form.validate(async valid => {
        if (!valid) {
          return this.$message.error('请正确填写信息')
        }
        let option = {
          url: 'users/' + this.editUserForm.id,
          type: 'put',
          data: this.editUserForm
        }
        let { data: res } = await request(option)
        //修改失败
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success('修改成功')
        //隐藏对话框
        this.editUserDialogVisible = false
        //重新加载数据
        this.getUserList()
      })
    },
    //10、根据用户的id删除用户
    async delUserById(user) {
      console.log(user)
      if (!user) {
        return
      }
      let role_name = user.role_name
      if (role_name === '超级管理员') {
        return this.$message.error('超级管理员不可删除')
      }
      //确认框 confirmRes=cancel/confirm
      let confirmRes = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定删除',
        //点击取消会抛出异常
        cancelButtonText: '取消删除',
        type: 'warning'
      }).catch(e => e)
      console.log(confirmRes)
      //如果点击的是取消，提示你取消了删除 this.$message.info("")
      if (confirmRes === 'cancel') {
        return this.$message.info('你取消了删除操作')
      }

      //如果点击是确定，执行用户删除操作，提示删除是否成功的消息this.$message.error("")/this.$message.success("")
      if (confirmRes === 'confirm') {
        let option = {
          url: 'users/' + user.id,
          type: 'delete'
        }
        let { data: res } = await request(option)
        console.log(res)
        this.$message.success('删除成功')
      }
      //重新加载页面的数据
      this.getUserList()
    }
  },

  mounted() {
    this.getUserList()
  }
}
</script>

<style lang="less" scoped>
.users-root {
  .el-card {
    margin-top: 0.2rem;
    .el-table {
      margin-top: 0.2rem;
    }
    .el-pagination {
      margin-top: 0.2rem;
    }
  }
}
</style>
